package com.exam.serviceimpl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.exam.util.HttpUtil;
import com.exam.service.FaceVerificationService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class FaceVerificationServiceImpl implements FaceVerificationService {
    private static final String WEBWFV_URL = "http://api.xfyun.cn/v1/service/v1/image_identify/face_verification";
    // 应用ID (必须为webapi类型应用，并开通人脸比对服务，参考帖子如何创建一个webapi应用：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
    private static final String APPID = "47a4f0a2";
    // 接口密钥(webapi类型应用开通人脸比对服务后，控制台--我的应用---人脸比对---相应服务的apikey)
    private static final String API_KEY = "474f062e402943b9a617137e4d65948b";
    @Override
    public String faceVerification(MultipartFile file1, MultipartFile file2) throws IOException, JSONException {
        Map<String, String> header = buildHttpHeader();

        // 直接从MultipartFile对象中读取图片并Base64编码
        byte[] imageByteArray1 = file1.getBytes(); // 使用MultipartFile的getBytes方法
        String imageBase641 = Base64.encodeBase64String(imageByteArray1); // 使用Base64的encodeBase64String方法
        byte[] imageByteArray2 = file2.getBytes();
        String imageBase642 = Base64.encodeBase64String(imageByteArray2);

        // 对Base64编码后的字符串进行URL编码
        String encodedImage1 = URLEncoder.encode(imageBase641, "UTF-8");
        String encodedImage2 = URLEncoder.encode(imageBase642, "UTF-8");

        // 构建POST请求的参数
        String postParams = "first_image=" + encodedImage1 + "&" + "second_image=" + encodedImage2;

        // 发送POST请求并获取结果
        String result = HttpUtil.doPost1(WEBWFV_URL, header, postParams);
        return result;
    }
    private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException, JSONException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        JSONObject param = new JSONObject();
        param.put("get_image", true);
        String params = param.toString();
        String paramBase64 = new String(Base64.encodeBase64(params.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", APPID);
        return header;
    }
}
